package cn.edu.nchu.service.impl;

import cn.edu.nchu.entity.utils.JSONUtil;
import cn.edu.nchu.service.DeviceMessageService;
import cn.edu.nchu.stream.MySink;
import cn.edu.nchu.stream.MySource;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service
@EnableBinding({MySource.class, MySink.class})
public class DeviceMessageServiceImpl implements DeviceMessageService {
    @Autowired
    private MySource mySource;

    @Override
    public void sendMessage(JSONObject message) {
        mySource.message_down().send(MessageBuilder.withPayload(message).build());
    }

    @Override
    public void requestCommand(JSONObject request) {
        mySource.commands_request().send(MessageBuilder.withPayload(request).build());
    }

    @Override
    @StreamListener(value = MySink.MESSAGES_UP)
    public void reciveMessage(JSONObject message) {
        System.out.println("设备消息上报：" + message.toJSONString());
        sendMessage(JSONUtil.str2JSONObject("消息已收到！！！"));
    }

    @Override
    @StreamListener(value = MySink.PROPERTIES_REPORT)
    public void reciveProperties(JSONObject properties) {
        System.out.println("设备上报属性数据：" + properties.toJSONString());
    }

    @Override
    @StreamListener(value = MySink.COMMANDS_RESPONSE)
    public void responseCommand(JSONObject response) {
        System.out.println("设备返回命令响应：" + response.toJSONString());
    }
}
